<template>
  <view class="book-detail-container">
    <!-- 顶部图书信息 -->
    <view class="book-header">
      <view class="book-cover-wrapper">
        <image class="book-cover" :src="book.cover" mode="aspectFill"></image>
        <view class="book-status" v-if="book.status">{{book.status}}</view>
      </view>

      <view class="book-meta">
        <view class="book-title">{{book.title}}</view>
        <view class="book-author">作者: {{book.author || '未知'}}</view>
        <view class="book-isbn">ISBN: {{book.isbn || '暂无'}}</view>

        <view class="meta-row">
          <text class="meta-item">出版社: {{book.publisher || '未知'}}</text>
          <text class="meta-divider">|</text>
          <text class="meta-item">出版时间: {{book.publishTime || '未知'}}</text>
        </view>

        <view class="meta-row">
          <text class="meta-item">页数: {{book.pages || '未知'}}</text>
          <text class="meta-divider">|</text>
          <text class="meta-item">定价: {{book.price ? `¥${book.price}` : '未知'}}</text>
        </view>
      </view>
    </view>

    <!-- 操作按钮 -->
    <view class="book-actions">
      <view class="action-btn" @click="toggleFavorite">
        <uni-icons :type="isFavorite ? 'heart-filled' : 'heart'" size="20" :color="isFavorite ? '#f56c6c' : '#666'">
        </uni-icons>
        <text>{{isFavorite ? '已收藏' : '收藏'}}</text>
      </view>
      <view class="action-btn" @click="showFeedback">
        <uni-icons type="compose" size="20" color="#666"></uni-icons>
        <text>纠错</text>
      </view>
      <view class="action-btn" @click="shareBook">
        <uni-icons type="redo" size="20" color="#666"></uni-icons>
        <text>分享</text>
      </view>
    </view>

    <!-- 内容简介 -->
    <view class="section">
      <view class="section-title">内容简介</view>
      <view class="section-content">
        {{book.description || '暂无内容简介'}}
      </view>
    </view>

    <!-- 目录预览 -->
    <view class="section" v-if="book.catalog && book.catalog.length">
      <view class="section-title">目录</view>
      <view class="catalog-preview">
        <view class="catalog-item" v-for="(item, index) in book.catalog.slice(0, 5)" :key="index">
          {{item}}
        </view>
        <view class="view-more" @click="showFullCatalog" v-if="book.catalog.length > 5">
          查看更多目录...
        </view>
      </view>
    </view>

    <!-- 读者评论 -->
    <view class="section">
      <view class="section-title">读者评论</view>
      <view class="comment-list" v-if="comments.length">
        <view class="comment-item" v-for="comment in comments" :key="comment.id">
          <image class="comment-avatar" :src="comment.avatar" mode="aspectFill"></image>
          <view class="comment-content">
            <view class="comment-user">{{comment.user}}</view>
            <view class="comment-text">{{comment.content}}</view>
            <view class="comment-time">{{comment.time}}</view>
          </view>
        </view>
      </view>
      <view class="empty-comment" v-else>
        <uni-icons type="chat" size="24" color="#ccc"></uni-icons>
        <text>暂无评论</text>
      </view>
      <view class="add-comment" @click="showCommentInput">
        我要评论
      </view>
    </view>

    <!-- 底部操作栏 -->
    <view class="bottom-bar">
      <button class="btn-shelf" :class="{'btn-remove': inShelf}" @click="toggleShelf">
        {{inShelf ? '移出书架' : '加入书架'}}
      </button>
      <button class="btn-read" type="warn" @click="readBook">立即阅读</button>
    </view>
  </view>
</template>

<script>
  import {
    mapState,
    mapMutations
  } from 'vuex'

  export default {
    data() {
      return {
        book: {
          id: null,
          title: '',
          cover: '',
          author: '',
          isbn: '',
          publisher: '',
          publishTime: '',
          pages: '',
          price: '',
          description: '',
          catalog: [],
          status: ''
        },
        comments: [{
            id: 1,
            content: '特别好看的一本书！！！',
            time: '20t25-04-09',
            user: '书迷小王',
            avatar: '/static/tabbar/my.png'
          },
          {
            id: 2,
            content: '这本真的很难不爱！！！',
            time: '2025-04-09',
            user: '书迷小张',
            avatar: '/static/tabbar/my.png'
          }
        ],
        isFavorite: false,
        isLoading: false
      }
    },
    computed: {
      ...mapState('m_book', ['bookList']),
      inShelf() {
        return this.book.id && this.bookList.some(item => item.id === this.book.id)
      }
    },
    methods: {
      ...mapMutations('m_book', ['addToBookList', 'removeBookByIds']),

      async fetchBookDetail(id) {
        this.isLoading = true
        try {
          const {
            data
          } = await uni.$http.get(`/book/detail/${id}`)
          if (data.code !== 1) throw new Error(data.message || '获取图书详情失败')

          this.book = {
            ...this.book,
            ...data.data,
            catalog: data.data.catalog ? data.data.catalog.split('\n') : []
          }

          // 获取收藏状态
          await this.checkFavoriteStatus()


          // 获取评论
          await this.fetchComments()

        } catch (error) {
          console.error('获取图书详情失败:', error)
          uni.showToast({
            title: error.message || '获取图书详情失败',
            icon: 'none'
          })
        } finally {
          this.isLoading = false
        }
      },

      async checkFavoriteStatus() {
        // 这里调用API检查收藏状态
        // const { data } = await uni.$http.get(`/book/favorite/status?id=${this.book.id}`)
        // this.isFavorite = data.isFavorite
      },

      async fetchComments() {
        /* try {
          const {
            data
          } = await uni.$http.get(`/book/comments?id=${this.book.id}`)
          if (data.code === 1) {
            this.comments = data.data || []
          }
        } catch (error) {
          console.error('获取评论失败:', error)
        } */
      },

      async toggleFavorite() {
        try {
          this.isFavorite = !this.isFavorite
          // 调用API更新收藏状态
          // await uni.$http.post(`/book/favorite`, {
          //   bookId: this.book.id,
          //   status: this.isFavorite
          // })
          uni.showToast({
            title: this.isFavorite ? '已加入收藏' : '已取消收藏',
            icon: 'none'
          })
        } catch (error) {
          this.isFavorite = !this.isFavorite
          console.error('操作失败:', error)
          uni.showToast({
            title: '操作失败，请重试',
            icon: 'none'
          })
        }
      },

      showFeedback() {
        uni.navigateTo({
          url: `/subpkg/feedback/feedback?bookId=${this.book.id}`
        })
      },

      shareBook() {
        uni.share({
          title: this.book.title,
          content: `推荐《${this.book.title}》给你，作者：${this.book.author}`,
          href: `/pages/book-detail/book-detail?id=${this.book.id}`,
          success: () => {
            uni.showToast({
              title: '分享成功',
              icon: 'none'
            })
          }
        })
      },

      showFullCatalog() {
        uni.showModal({
          title: '图书目录',
          content: this.book.catalog.join('\n'),
          showCancel: false
        })
      },

      showCommentInput() {
        uni.navigateTo({
          url: `/subpkg/add_review/add_review?id=${this.book.id}`
        })
      },

      async toggleShelf() {

        if (this.inShelf) {
          await this.removeFromShelf()
        } else {
          await this.addToShelf()
        }
      },

      async addToShelf() {
        try {
          const {
            data
          } = await uni.$http.post(`/book/add/${this.book.id}`)
          if (data.code !== 1) throw new Error(data.message || '添加失败')

          this.addToBookList(this.book)
          uni.showToast({
            title: '已加入书架',
            icon: 'none'
          })
        } catch (error) {
          console.error('添加失败:', error)
          uni.showToast({
            title: error.message || '添加失败',
            icon: 'none'
          })
        }
      },

      async removeFromShelf() {
        try {
          const [err, res] = await uni.showModal({
            title: '提示',
            content: '确定要移出书架吗？'
          })

          if (!res.confirm) return

          const {
            data
          } = await uni.$http.delete(`/book/delete?ids=${this.book.id}`)
          if (data.code !== 1) throw new Error(data.message || '移除失败')

          this.removeBookByIds([this.book.id])
          uni.showToast({
            title: '已移出书架',
            icon: 'none'
          })
        } catch (error) {
          console.error('移除失败:', error)
          uni.showToast({
            title: error.message || '移除失败',
            icon: 'none'
          })
        }
      },

      readBook() {
        uni.navigateTo({
          url: `/subpkg/view/view?data=${encodeURIComponent(JSON.stringify({
         id: this.book.id,
         title: this.book.title,
         src: this.book.cover
       }))}`
        })
      }
    },
    onLoad(options) {
      uni.setNavigationBarTitle({
        title: decodeURIComponent(options.title)
      })

      if (options.id) {
        this.fetchBookDetail(options.id)
      }
    }
  }
</script>

<style lang="scss">
  .book-detail-container {
    padding-bottom: 100rpx;
    min-height: 100vh;
    background-color: #f8f8f8;

    .book-header {
      display: flex;
      padding: 30rpx;
      background-color: #fff;
      margin-bottom: 20rpx;

      .book-cover-wrapper {
        position: relative;
        margin-right: 30rpx;

        .book-cover {
          width: 200rpx;
          height: 266rpx;
          border-radius: 8rpx;
          box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
        }

        .book-status {
          position: absolute;
          top: 0;
          right: 0;
          background-color: #f56c6c;
          color: #fff;
          font-size: 20rpx;
          padding: 4rpx 12rpx;
          border-bottom-left-radius: 8rpx;
          border-top-right-radius: 8rpx;
        }
      }

      .book-meta {
        flex: 1;

        .book-title {
          font-size: 32rpx;
          font-weight: bold;
          color: #333;
          margin-bottom: 16rpx;
          line-height: 1.4;
        }

        .book-author,
        .book-isbn {
          font-size: 26rpx;
          color: #666;
          margin-bottom: 12rpx;
        }

        .meta-row {
          display: flex;
          align-items: center;
          margin-bottom: 10rpx;
          font-size: 24rpx;
          color: #888;

          .meta-divider {
            margin: 0 10rpx;
          }
        }
      }
    }

    .book-actions {
      display: flex;
      background-color: #fff;
      padding: 20rpx 0;
      margin-bottom: 20rpx;

      .action-btn {
        flex: 1;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        font-size: 24rpx;
        color: #666;

        .uni-icons {
          margin-bottom: 8rpx;
        }
      }
    }

    .section {
      background-color: #fff;
      margin-bottom: 20rpx;
      padding: 0 30rpx;

      .section-title {
        font-size: 30rpx;
        font-weight: bold;
        color: #333;
        padding: 25rpx 0;
        border-bottom: 1rpx solid #eee;
      }

      .section-content {
        padding: 25rpx 0;
        font-size: 28rpx;
        color: #333;
        line-height: 1.6;
      }

      .catalog-preview {
        padding: 25rpx 0;

        .catalog-item {
          font-size: 26rpx;
          color: #666;
          padding: 10rpx 0;
          border-bottom: 1rpx dashed #eee;
        }

        .view-more {
          font-size: 26rpx;
          color: #1989fa;
          text-align: center;
          padding: 20rpx 0;
        }
      }

      .comment-list {
        padding: 20rpx 0;

        .comment-item {
          display: flex;
          padding: 20rpx 0;
          border-bottom: 1rpx solid #f5f5f5;

          .comment-avatar {
            width: 80rpx;
            height: 80rpx;
            border-radius: 50%;
            margin-right: 20rpx;
          }

          .comment-content {
            flex: 1;

            .comment-user {
              font-size: 26rpx;
              color: #666;
              margin-bottom: 10rpx;
            }

            .comment-text {
              font-size: 28rpx;
              color: #333;
              margin-bottom: 10rpx;
              line-height: 1.5;
            }

            .comment-time {
              font-size: 22rpx;
              color: #999;
            }
          }
        }
      }

      .empty-comment {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        padding: 60rpx 0;
        color: #ccc;
        font-size: 26rpx;

        .uni-icons {
          margin-bottom: 20rpx;
        }
      }

      .add-comment {
        font-size: 28rpx;
        color: #1989fa;
        text-align: center;
        padding: 25rpx 0;
        border-top: 1rpx solid #eee;
      }
    }

    .bottom-bar {
      position: fixed;
      bottom: 0;
      left: 0;
      right: 0;
      display: flex;
      height: 100rpx;
      background-color: #fff;
      box-shadow: 0 -2rpx 12rpx rgba(0, 0, 0, 0.08);
      z-index: 10;

      .btn-shelf {
        flex: 1;
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 30rpx;
        color: #333;
        background-color: #fff;
        border-radius: 0;

        &.btn-remove {
          color: #f56c6c;
        }
      }

      .btn-read {
        flex: 1;
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 30rpx;
        color: #fff;
        background-color: #f56c6c;
        border-radius: 0;
      }
    }
  }
</style>
